import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { message, Modal, Select } from 'antd';
import axios from 'axios'
import PropTypes from 'prop-types';
import ScrollArea from 'react-scrollbar';
import { createFolder, renameFile, renameFolder } from '../../../../../../api';
import { COMMON_SUCCESS_STATE, DIRECTORIES, FILES } from '../../../../../../constant';
import directory from './../../../../../../asserts/ic_file2.png';
import { bytesToSize, dateFormat } from '../../../../../../utils/commonUtils';
import { setFolder } from '../../../../../../redux/actions/folder';
import FileDataMenu from '../FileDataMenu';
import { showFileDataMenu } from '../../../../../../redux/actions/fileDataMenu';
import 'antd/lib/message/style';
import 'antd/lib/modal/style';
import 'antd/lib/select/style';
import './index.less';
import { setFiles } from '../../../../../../redux/actions/files';

const { Option } =  Select
class DataGrid extends PureComponent {

  static propTypes = {
    style: PropTypes.object,
    isCreateFolder: PropTypes.bool,
    changeCreateFolderStatus: PropTypes.func,
    files: PropTypes.object,
    category: PropTypes.object,
    folder: PropTypes.object,
    setFolder: PropTypes.func,
    showFileDataMenu: PropTypes.func,
    setFiles: PropTypes.func
  };

  state = {
    curFile: [],
    shareVisible: false,
    checkedAll: false,
    checkedCount: 0,
    sortObject: {
      type: 0, // 0:文件名称 1:修改时间 2:文件大小
      sort: 'up' // up:升序 down:降序
    }
  }
  ;

  // 创建文件夹
  createFolder = async (input) => {
    const {
      changeCreateFolderStatus,
      category,
      folder
    } = this.props;
    let value = input.value;
    if (value.trim()) {
      let parentId = folder.id || 0;
      // 发送请求创建文件夹
      let { code } = await createFolder({
        name: value,
        parentId
      });
      if (code === COMMON_SUCCESS_STATE) {
        input.value = '';
        changeCreateFolderStatus(false);
        // 点击当前菜单重新渲染页面
        category.target.click();
      } else {
        message.error('创建文件夹失败');
      }
    } else {
      message.warn('请输入文件夹名称');
    }
  };

  // 取消创建文件夹
  cancelFolder = (input) => {
    const { changeCreateFolderStatus } = this.props;
    input.value = '';
    changeCreateFolderStatus(false);
  };

  // 进入文件夹
  enterFolder = (item, event) => {
    event.stopPropagation()
    // 设置redux中当前文件夹
    const {
      setFolder,
      category
    } = this.props;
    setFolder(item);
    // 点击当前菜单项，刷新数据, 延迟点击，保证获取到最新的父分类id
    setTimeout(() => {
      category.target.click();
    }, 10)
  };

  // 显示菜单项
  showFileDataMenu = (event) => {
    event.stopPropagation()
    if (event.button === 2) {
      const { showFileDataMenu } = this.props
      let x = event.clientX
      let y = event.clientY
      showFileDataMenu({
        x,
        y,
        visible: true
      })
    }
  }

  // 显示分享界面
  showShare = (event) => {
    event.stopPropagation()
    this.setState({
      shareVisible: true
    })
  }

  // mini菜单显示
  showMiniMenu = (event) => {
    event.stopPropagation()
    let ele = event.target
    let className = ele.className
    if (className.indexOf('active') !== -1) {
      className = className.replace(' active', '')
    } else {
      className = className + ' active'
    }
    ele.className = className
  }

  shareCreate = () => {

  }

  shareCancel = () => {
    this.setState({
      shareVisible: false
    })
  }

  handleTimeOut = () => {
    console.log(11);
  }

  // axios 下载文件，监听进度条事件
  download = async (id, type, event) => {
    event.stopPropagation()
    // 下载文件，不易封装
    axios.get(`files/download/${type}/${id}`, {
      responseType: 'blob',
      onDownloadProgress: function (event) {
        console.log(event);
      }
    })
      .then((res) => {
        // 请求头中文件类型
        // eslint-disable-next-line no-unused-vars
        let type = res.headers['content-type'];
        // 请求头中文件名
        // eslint-disable-next-line no-unused-vars
        let name = res.headers['content-disposition'].split(';')[1].split('=')[1]
        // eslint-disable-next-line no-unused-vars
        const blob = new Blob([res.data]);
        // a元素中是否存在download属性，存在则使用非ie
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const eLink = document.createElement('a');
          eLink.download = name;
          eLink.style.display = 'none';
          eLink.href = URL.createObjectURL(blob);
          document.body.appendChild(eLink);
          eLink.click();
          URL.revokeObjectURL(eLink.href); // 释放URL 对象
          document.body.removeChild(eLink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, name);
        }
      })
      .catch((e) => {
        console.log(e);
      })
  }

  // 选中与否文件
  changeCheckFile = (index, type, event) => {
    event.stopPropagation()
    const { files, setFiles} = this.props
    files[type][index].checked = event.target.checked
    setFiles(files)
  }

  // 全选与取消
  changeCheckAllFiles = (event) => {
    event.stopPropagation()
    const { files, setFiles } = this.props
    let checked = event.target.checked
    this.setState({
      checkedAll: checked
    })
    // 设置文件选中
    this.setFilesCheck(files, checked)
    setFiles(files)
  }

  // 设置文件默认未选中样式
  setFilesCheck = (files, checked) => {
    files[FILES].forEach((item) => item.checked = checked)
    files[DIRECTORIES].forEach((item) => item.checked = checked)
  }

  // 排序字段
  sort = (type, event) => {
    event.stopPropagation()
    const { sortObject } = this.state
    if (sortObject.type === type) {
      // 切换排序顺序
      this.setState((state) => ({sortObject: {
        type,
        sort: state.sortObject.sort === 'up'? 'down': 'up'
      }}))
    } else {
      this.setState({
        sortObject: {
          type,
          sort: 'up'
        }
      })
    }
  }

  // 改变输入框input值，受控组件
  changeInputValue = (index, type, event) => {
    event.stopPropagation()
    const { files, setFiles} = this.props
    files[type][index].input = event.target.value
    setFiles(files)
  }

  // 发送请求重命名文件
  renameFile = async (id, name, type, event) => {
    if (!name.trim()) {
      message.error('请输入文件名称')
      return false
    }
    const { category } = this.props
    event.stopPropagation()
    if (type === DIRECTORIES) {
      let { code } = await renameFolder(id, name);
      if (code !== COMMON_SUCCESS_STATE) {
        message.error('文件夹重命名失败');
        return false;
      }
    } else if (type === FILES) {
      let { code } = await renameFile(id, name);
      if (code !== COMMON_SUCCESS_STATE) {
        message.error('文件重命名失败');
        return false;
      }
    }
    category.target.click()
  }

  // 取消创建文件
  cancelFile = (index, type, event) => {
    event.stopPropagation()
    const { files, setFiles} = this.props
    files[type][index].input = ''
    files[type][index].rename = false
    setFiles(files)
  }

  render () {
    const {
      style,
      isCreateFolder,
      files: allFiles
    } = this.props;
    const {
      shareVisible,
      sortObject
    } = this.state
    // 目录
    const directories = allFiles[DIRECTORIES];
    // 文件
    const files = allFiles[FILES];
    return (
      <>
        <ul className="dataGrid" style={style}>
          {/* 头部*/}
          <li className="dataGrid_header">
            <input className="dataGridCheck" type="checkbox"
              checked={allFiles.checkedAll || this.state.checkedAll}
              onChange={this.changeCheckAllFiles}/>
            <div onClick={(event) => this.sort(0, event)} className={`dataGridDesc ${sortObject.type === 0? 'active ': ' '} ${sortObject.sort}`}>
              {
                allFiles.checkedCount === 0
                  ?<span>
                文件名称
                  </span>
                  :<span>
                    {
                      `已选择${allFiles.checkedCount}个文件/文件名称`
                    }
                  </span>
              }
              <span className="sort">
                <i className="iconfont icon icon-arrow-up"/>
                <i className="iconfont icon icon-arrow-down"/>
              </span>
            </div>
            <div onClick={(event) => this.sort(1, event)} className={`dataGridUpdateTime ${sortObject.type === 1? 'active ': ' '} ${sortObject.sort}`}>
              <span>
                修改时间
              </span>
              <span className="sort">
                <i className="iconfont icon icon-arrow-up"/>
                <i className="iconfont icon icon-arrow-down"/>
              </span>
            </div>
            <div onClick={(event) => this.sort(2, event)} className={`dataGridSize ${sortObject.type === 2? 'active ': ' '} ${sortObject.sort}`}>
              <span>
                大小
              </span>
              <span className="sort">
                <i className="iconfont icon icon-arrow-up"/>
                <i className="iconfont icon icon-arrow-down"/>
              </span>
            </div>
          </li>
          <ScrollArea
            smoothScrolling
            speed={0.8}
            className="area"
          >
            {
              isCreateFolder
                ? <li className="dataGrid_main create_folder">
                  <input className="dataGridCheck" type="checkbox" disabled/>
                  <div className="dataGridDesc">
                    <div className="imageBox">
                      <img src={directory} alt=""/>
                    </div>
                    <span className="inputFilenameBox">
                      <input ref={(folderInput) => this.folderInput = folderInput}
                        onKeyUp={(event) => {
                          console.log(event.keyCode);
                          if (event.keyCode === 13) {
                            this.createFolder(this.folderInput)
                          } else if (event.keyCode === 27) {
                            this.cancelFolder(this.folderInput)
                          }
                        }}
                        type="text"
                        autoFocus/>
                      <i className="iconfont icon-check"
                        onClick={() => this.createFolder(this.folderInput)}/>
                      <i className="iconfont icon-close"
                        onClick={() => this.cancelFolder(this.folderInput)}/>
                    </span>
                  </div>
                  <div className="dataGridUpdateTime">
                    <div className="dataGridTime">
                      -
                    </div>
                  </div>
                  <div className="dataGridSize">
                    -
                  </div>
                </li>
                : ''
            }

            {
              // 文件夹遍历
              directories
                ? directories.map((item, index) => (
                  <li key={item.id} className={`dataGrid_main ${item.checked? 'checked': ''}`}
                    onMouseUp={this.showFileDataMenu}>
                    <input className="dataGridCheck"
                      type="checkbox"
                      checked={item.checked}
                      onChange={(event) => this.changeCheckFile(index, DIRECTORIES, event)}/>
                    <div className="dataGridDesc">
                      <div className="imageBox">
                        <img src={item.url} alt=""/>
                      </div>
                      {
                        !item.rename
                          ?<span onClick={(event) => this.enterFolder(item, event)}>{item.name}</span>
                          :<span className='inputFilenameBox'>
                            <input autoFocus value={item.input}
                              onKeyUp={(event) => {
                                if (event.keyCode === 13) {
                                  this.renameFile(item.id, item.input, DIRECTORIES, event)
                                } else if (event.keyCode === 27) {
                                  this.cancelFile(index, DIRECTORIES, event)
                                }
                              }}
                              onInput={(event) => this.changeInputValue(index, DIRECTORIES, event)}/>
                            <i className="iconfont icon-check" onClick={(event) => this.renameFile(item.id, item.input, DIRECTORIES, event)}/>
                            <i className="iconfont icon-close" onClick={(event) => this.cancelFile(index, DIRECTORIES, event)}/>
                          </span>
                      }
                    </div>
                    <div className="dataGridUpdateTime">
                      <div className="dataGridTime">
                        {
                          dateFormat('yyyy-MM-dd hh:mm', new Date(item.updateTime))
                        }
                      </div>
                      <div className="dataGridLink">
                        <a title="分享" className="iconfont icon icon-share" onClick={this.showShare}/>
                        <a title="更多" className="iconfont icon icon-more" onMouseUp={(event) => event.stopPropagation()}  onClick={this.showMiniMenu}>
                          <ul className="miniFileDataMenu">
                            <li>
                              <i className="iconfont icon-enjoy-together" />
                              共享
                            </li>
                            <li>
                              <i className="iconfont icon-delete" />
                              删除
                            </li>
                            <li>
                              <i className="iconfont icon-rename" />
                              重命名
                            </li>
                            <li>
                              <i className="iconfont icon-copy" />
                              复制
                            </li>
                            <li>
                              <i className="iconfont icon-move" />
                              移动
                            </li>
                          </ul>
                        </a>
                      </div>
                    </div>
                    <div className="dataGridSize">
                      -
                    </div>
                  </li>
                ))
                : ''
            }
            {
              // 文件遍历
              files
                ? files.map((item, index) => (
                  <li key={item.id}
                    className={`dataGrid_main ${item.checked? 'checked': ''}`}
                    onMouseUp={this.showFileDataMenu}>
                    <input className="dataGridCheck"
                      checked={item.checked}
                      type="checkbox"
                      onChange={(event) => this.changeCheckFile(index, FILES, event)}/>
                    <div className="dataGridDesc">
                      <div className="imageBox" style={{padding: (item.contentType.indexOf('image') !== -1) ? '8px' : '0'}}>
                        <img src={(item.contentType.indexOf('image') !== -1) ? item.accessPath: item.url} alt=""/>
                      </div>
                      {
                        !item.rename
                          ?<span>{item.name}</span>
                          :<span className='inputFilenameBox'>
                            <input autoFocus  value={item.input}
                              onKeyUp={(event) => {
                                if (event.keyCode === 13) {
                                  this.renameFile(item.id, item.input, DIRECTORIES, event)
                                } else if (event.keyCode === 27) {
                                  this.cancelFile(index, DIRECTORIES, event)
                                }
                              }}
                              onInput={(event) => this.changeInputValue(index, FILES, event)}/>
                            <i className="iconfont icon-check" onClick={(event) => this.renameFile(item.id, item.input, FILES, event)}/>
                            <i className="iconfont icon-close" onClick={(event) => this.cancelFile(index, FILES, event)}/>
                          </span>
                      }
                    </div>
                    <div className="dataGridUpdateTime">
                      <div className="dataGridTime">
                        {
                          dateFormat('yyyy-MM-dd hh:mm', new Date(item.updateTime))
                        }
                      </div>
                      <div className="dataGridLink">
                        <a title="分享" className="iconfont icon icon-share" onClick={this.showShare}/>
                        <a title="下载" className="iconfont icon icon-download" href={item.accessPath} target="_blank" rel="noreferrer"/>
                        <a title="更多" className="iconfont icon icon-more" onMouseUp={(event) => event.stopPropagation()} onClick={this.showMiniMenu}>
                          <ul className="miniFileDataMenu">
                            <li>
                              <i className="iconfont icon-enjoy-together" />
                              共享
                            </li>
                            <li>
                              <i className="iconfont icon-delete" />
                              删除
                            </li>
                            <li>
                              <i className="iconfont icon-rename" />
                              重命名
                            </li>
                            <li>
                              <i className="iconfont icon-copy" />
                              复制
                            </li>
                            <li>
                              <i className="iconfont icon-move" />
                              移动
                            </li>
                          </ul>
                        </a>
                      </div>
                    </div>
                    <div className="dataGridSize">
                      {
                        bytesToSize(item.size)
                      }
                    </div>
                  </li>
                ))
                : ''
            }

          </ScrollArea>
        </ul>
        <FileDataMenu/>
        <Modal bodyStyle={{ borderRadius: '6ox' }}
          okText="创建链接"
          cancelText="取消创建"
          title="分享文件(夹):seata-server-1.1.0.zip"
          visible={shareVisible}
          onOk={this.shareCreate} onCancel={this.shareCancel}>
          <p style={{fontSize: '12px', fontWeight: '700', marginBottom: '20px' }}>选择链接有效期</p>
          <Select defaultValue="7" style={{ width: 120 }} onChange={this.handleTimeOut}>
            <Option value="100">永久有效</Option>
            <Option value="7">7天</Option>
            <Option value="1">1天</Option>
          </Select>
        </Modal>
      </>
    );
  }
}

export default connect(
  (state) => ({
    files: state.files,
    category: state.category,
    folder: state.folder
  }),
  {
    setFolder,
    setFiles,
    showFileDataMenu
  }
)(DataGrid);
